/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package net.hnilica.cisteniulic.servlet;

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.RequestDispatcher;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import net.hnilica.cisteniulic.dao.OsobaDAO;
import net.hnilica.cisteniulic.dao.Postman;
import net.hnilica.cisteniulic.dto.Osoba;

/**
 *
 * @author swosh
 */
public class Registration extends HttpServlet implements Servlet {
    private static final String urlSuccess = "/CisteniUlic/index.jspx?akce=uspesnaregistrace";
    private static final String urlFail = "/index.jspx?akce=registrace";
    protected Logger log = Logger.getLogger(getClass().getName());
    private String email;
    private String heslo;
    private String potvrzeni;
    private String kaptcha;
    private String kaptchaKey;

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @return boolean indicates whether validation is ok
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected boolean procesValidation(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String noMakeNewKaptcha = "false";
        email = request.getParameter("email").toString().trim();
        request.setAttribute("email", email);
        heslo = request.getParameter("heslo").toString();
        potvrzeni = request.getParameter("potvrzeni").toString();
        kaptcha = request.getParameter("kaptcha").toString().trim();

        HttpSession session = request.getSession(true);
        try {
            noMakeNewKaptcha = (String) session.getAttribute("noMakeNewKaptcha");
        } catch (NullPointerException e) {
            noMakeNewKaptcha = "false";
        }
        boolean noMakeNewKaptchaB = Boolean.parseBoolean(noMakeNewKaptcha);

        try {
            kaptchaKey = (noMakeNewKaptchaB) ? session.getAttribute("kaptchaKey").toString()
                    : session.getAttribute("KAPTCHA_SESSION_KEY").toString();
        } catch (NullPointerException nullE1) {
            try {
                kaptchaKey = session.getAttribute("KAPTCHA_SESSION_KEY").toString();
            } catch (NullPointerException nullE2) {
                kaptchaKey = "";
                log.log(Level.SEVERE, "Chyba u session u kaptchy. Nemělo by nastat. Snad záměnou pořadí KaptchaServletMy a Registration", nullE2);
            }
        }


        //Reset errors.
        request.setAttribute("chyba", "");
        request.setAttribute("chybaremail", "");
        request.setAttribute("chybarheslo", "");
        request.setAttribute("chybarpotvrzeni", "");
        request.setAttribute("chybarkaptcha", "");
        //
        String chybaremail = "";
        String chybarheslo = "";
        String chybarpotvrzeni = "";
        String chybarkaptcha = "";
        String chyba = "";

        //If validation ok. Ok stays true.
        boolean ok = true;

        Pattern pat = Pattern.compile("^([a-zA-Z0-9_\\.\\-])+@(([a-zA-Z0-9\\-])+\\.)+([a-zA-Z0-9]{2,4})+$");
        Matcher mat = pat.matcher(email);
        try {
            if (!mat.matches()) {
                chybaremail += "Email je ve špatném tvaru. Měl by být např. jmeno@slovo.cz. ";
                ok = false;
            }
            if (email.length() > 64) {
                chybaremail += "Email je moc dlouhý, max je 64 znaků. ";
                ok = false;
            }
            if (heslo.length() > 64) {
                chybarheslo += "Heslo je moc dlouhé, max je 64 znaků. ";
                ok = false;
            }
            if (heslo.length() < 8) {
                chybarheslo += "Heslo je moc krátké, min je 8 znaků. ";
                ok = false;
            }
            if (!heslo.equals(potvrzeni)) {
                chybarpotvrzeni += "Potvzení hesla není shodné s heslem. Musí být stejné. ";
                ok = false;
            }
            if (!kaptcha.equals(kaptchaKey)) {
                chybarkaptcha += "Špatně opsaný kód z obrázku. ";
                session.setAttribute("noMakeNewKaptcha", "false");//so make new kapcha...ou czech language
                session.setAttribute("kaptchaKey", "");
                ok = false;
            } else {
                session.setAttribute("noMakeNewKaptcha", "true");
                session.setAttribute("kaptchaKey", kaptchaKey);
            }
        } catch (Exception e) {
            log.log(Level.SEVERE, "Chyba při validaci.", e);
            chyba += "Něco se nepovedlo při ukládání. Zkuste to znova.";
            ok = false;
        }

        request.setAttribute("chyba", chyba);
        request.setAttribute("chybaremail", chybaremail);
        request.setAttribute("chybarheslo", chybarheslo);
        request.setAttribute("chybarpotvrzeni", chybarpotvrzeni);
        request.setAttribute("chybarkaptcha", chybarkaptcha);

        return ok;



    }

    private boolean procesSaving(HttpServletRequest request, HttpServletResponse response) {
        boolean isSaved = false;
        boolean hasSomeSameEmail = false;
        OsobaDAO osobaDAO = new OsobaDAO();
        Osoba oldOsoba = new Osoba();
        try {
            oldOsoba = osobaDAO.getOsobaWOHesloAktHex(email);
            if (oldOsoba.getEmail().equalsIgnoreCase(email)) {
                hasSomeSameEmail = true;
                request.setAttribute("chyba", " Někdo už má stejný email");
                return false;
            }
        } catch (NullPointerException e) {
            hasSomeSameEmail = false;
        }
        Osoba newOsoba = new Osoba();
        newOsoba.setEmail(email);
        newOsoba.setHeslo(heslo);
        isSaved = osobaDAO.saveOsoba(newOsoba);
        if (isSaved) {
            String aktHash = osobaDAO.getAktHash(email);
            boolean isMailed = new Postman().sendActivationMail(email, aktHash);
            if (isMailed) {
                return true;
            } else {
                request.setAttribute("chyba", " Něco se nepovedlo při posílání emailu. Zkuste to znova.");
                return false;
            }
        } else {
            request.setAttribute("chyba", " Něco se nepovedlo při ukládání. Zkuste to znova.");
            return false;
        }

    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("application/xhtml+xml;charset=UTF-8");
        request.setCharacterEncoding("UTF-8");
        boolean isSaved = false;
        boolean isValidatedOk = procesValidation(request, response);
        if (isValidatedOk) {
            isSaved = procesSaving(request, response);
        }
        if (isSaved) {

            response.sendRedirect(urlSuccess);
            return;
        }

        RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(urlFail);
        dispatcher.forward(request, response);
    }

}
